<template>
  <div class="cart">
    <!-- <h4>购物车</h4> -->
    <van-empty v-if="store.totalAmount === 0" class="custom-image"
      image="https://img.yzcdn.cn/vant/custom-empty-image.png" description="购物车为空，请选购商品">
      <van-button round type="primary" to="/">购物车为空，随便逛逛吧</van-button>
    </van-empty>

    <!-- 商品卡片 -->
    <van-swipe-cell v-for="item in store.cart">
      <van-card :price="item.price" desc="描述信息" :title="item.title">
        <template #thumb class="thumbBox">
          <van-checkbox v-model="item.check"></van-checkbox>
          <div class="van-image" style="width: 100%; height: 100%;">
            <img :src="item.image" class="van-image__img" style="object-fit: cover;">
          </div>
        </template>
        <template #num>
          <van-stepper theme="round" button-size="22" disable-input v-model="item.count" />
        </template>

      </van-card>
      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" @click="handleDelete(item.id)" />
      </template>
    </van-swipe-cell>


    <!-- 提交订单 -->
    <van-submit-bar :price="store.totalMoney * 100" button-text="提交订单" @Submit="handleSubmit">
      <van-checkbox @click="handleCheckAll" v-model="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script setup>
import useCartStore from '../../store/cart';
import useMenuStore from '../../store/menu'; 
import { ref, onUpdated } from 'vue';
import { useRouter } from 'vue-router';
import { Dialog } from 'vant';
import useUserStore from '../../store/user';
import 'vant/es/dialog/style';
const router = useRouter()
const userStore=useUserStore()
const rushStore =useMenuStore()
const store = useCartStore()
const checkAll = ref(store.checkAll)
const handleDelete = (id) => {
  store.cart = store.cart.filter(item => item.id !== id)
  store.totalAmount -= 1
}
const handleCheckAll = () => {
  console.log(store.checkAll)
  if (store.checkAll == true) {
    store.cart.forEach(item => item.check = false)
    checkAll.value = store.checkAll
  } else {
    store.cart.forEach(item => item.check = true)

  }

}
const handleSubmit = () => {
  rushStore.check=false
  if (store.cart.some(item => item.check == true)) {
    if(userStore.address[0]){
      router.push('/commit')
    }else{
      Dialog.alert({
      message: '请添加地址',
      theme: 'round-button',
    }).then(() => {
      router.push('/address')
    });
    }
  } else {
    Dialog.alert({
      message: '请至少选择一件商品。',
      theme: 'round-button',
    }).then(() => {
      
    });
  }
}


onUpdated(() => {
  checkAll.value = store.checkAll
})
</script>

<style lang="less"  scoped>
.cart {
  margin-bottom: 100px;
}

.van-submit-bar {
  margin-bottom: 48px;
}

:deep(.van-card__thumb) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 120px;

  img {
    width: 88px;
    height: 88px;
  }

  .van-checkbox {
    padding-right: 10px;
  }
}

.delete-button {
  height: 100%;
}
</style>
